//
//  TicherKeChengViewController.m
//  ZhiBoYuan
//
//  Created by coder_di on 2018/4/18.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "TicherKeChengViewController.h"
#import "TeacherKeChengTableViewCell.h"
#import "AdetailViewController.h"

@interface TicherKeChengViewController ()<UITableViewDelegate,UITableViewDataSource>


@property (nonatomic, strong)UIButton *weiKeBtn;

@property (nonatomic, strong)UIButton *zhiBoKeBtn;

@property (nonatomic, strong)UIView *leftLineView;

@property (nonatomic, strong)UIView *rightLineView;

//@property (nonatomic, strong)UITableView *tableView;
@property(nonatomic,strong)AxcEmptyDataTableView *tableView;

@property (nonatomic, strong)NSMutableArray *weikeArray;

@property (nonatomic, assign)BOOL isWeiKe;

@property (nonatomic, assign)int page;

@end

@implementation TicherKeChengViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"我的课程";
    
    _weikeArray = [NSMutableArray array];
    
    _isWeiKe = YES;
    
    _page = 1;
    
    [self loadData];
    
    
    [self setUI];
    
    [self addTableView];
    
    [self.tableView registerClass:[TeacherKeChengTableViewCell class] forCellReuseIdentifier:@"TeacherKeChengTableViewCell"];
    
}


-(void)loadData{
    
    [MBProgressHUD showLoadingImageToView:self.view];
    
    NSString *str ;
    
    if (_isWeiKe == YES) {
        str = @"2";
    }else{
        str = @"1";
    }
    SGParameter *parameter  = [[SGParameter alloc] init];
    
    parameter.body = @{@"type":str,
                       @"page":[NSString stringWithFormat:@"%d",_page],
                       @"page_count":@"10"
                       };
    
    NSString *lastUrl  = @"g=Client&m=Live&a=teacherLiveList";
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        NSDictionary *dic = responseObject;
        NSLog(@"%@",dic);
        if ([dic[@"status"] intValue] == 200) {
            for (NSDictionary *dicc in dic[@"data"][@"course_list"]) {
                [_weikeArray addObject:dicc];
            }
            
            if (_weikeArray.count < 4) {
                _tableView.mj_footer.hidden = YES;
            }else{
                _tableView.mj_footer.hidden = NO;
                
            }
            
            [self.tableView reloadData];
        }else{
            
            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0];
            
        }

        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}


-(void)addTableView {
    _tableView = [[AxcEmptyDataTableView alloc] initWithFrame:CGRectMake(0,52 * KscreenHeight + NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight - NAVIGATION_BAR_HEIGHT - 52 * KscreenHeight) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    _tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    
    
    __weak __typeof(&*self)weakSelf = self;
    
    // 下拉刷新
    _tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        weakSelf.page = 1;
        
        _weikeArray = [NSMutableArray array];
        
        [self loadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.tableView.mj_header endRefreshing];
            
        });
    }];
    
    //         上拉加载
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        _page = _page + 1;
        
        [self loadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [weakSelf.tableView.mj_footer endRefreshing];
            
        });
    }];
    
    
    self.placeholderView.frame = _tableView.bounds;
    
    // 设置空集时候展示的View
    _tableView.axcUI_placeHolderView = self.placeholderView;
    
    //  默认YES 自带渐入渐出动画效果，下边这个参数可以关闭
    _tableView.axcUI_placeHolderViewAnimations = NO;
    
    // 占位View的“重新加载”按钮的Block回调:
    __weak typeof(self) WeakSelf = self;
    
    self.placeholderView.clickLoadBtnBlock = ^(id type) {
        //        WeakSelf.dataArray = nil;
        
        weakSelf.page = 1;
        
        _weikeArray = [NSMutableArray array];
        
        [weakSelf loadData];
    };
    
    [self.view addSubview:_tableView];
}


-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{
    
    return 0;
    
}

#pragma mark -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  _weikeArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifity = @"MyKeCHengTableViewCell";
    //    MyIndentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifity];
    TeacherKeChengTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[TeacherKeChengTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifity];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
        cell.nameLable.text = [_weikeArray[indexPath.row] valueForKey:@"name"];
        cell.douLable.text = [NSString stringWithFormat:@"%@学豆",[_weikeArray[indexPath.row] valueForKey:@"price"]];
       [cell.imageVC sd_setImageWithURL:[NSURL URLWithString:[_weikeArray[indexPath.row] valueForKey:@"image_url"]] placeholderImage:[UIImage imageNamed:@"0009"]];
    if ([[_weikeArray[indexPath.row] valueForKey:@"is_free"] intValue] == 1) {
        cell.mianfeiLable.hidden = NO;
        cell.douLable.hidden = YES;
        cell.pingtaisyLable.hidden = YES;
    }else{
        cell.mianfeiLable.hidden = YES;
        cell.douLable.hidden = NO;
        cell.pingtaisyLable.hidden = NO;
        
    }
    
    CGFloat height = [self getLabelHeightWithText:cell.nameLable.text width:ScreenWidth - 200 * KscreenWidth font:15 * KscreenHeight];
    if (height > 20.0) {
        cell.nameLable.frame  = CGRectMake(190 * KscreenWidth, 20 * KscreenHeight, ScreenWidth - 200 * KscreenWidth, 40 * KscreenHeight);
    }else{
        cell.nameLable.frame  = CGRectMake(190 * KscreenWidth, 20 * KscreenHeight, ScreenWidth - 200 * KscreenWidth, 20 * KscreenHeight);
        cell.pingtaisyLable.frame = CGRectMake(190 * KscreenWidth, 45 * KscreenHeight, 85 *KscreenWidth, 18 * KscreenHeight);
        cell.mianfeiLable = [[UILabel alloc]initWithFrame:CGRectMake(190 * KscreenWidth, 40 * KscreenHeight, 100 *KscreenWidth, 25 * KscreenHeight)];
        cell.douLable.frame = CGRectMake(285 * KscreenWidth, 40 * KscreenHeight, 100 *KscreenWidth, 25 * KscreenHeight);
    }
    
    return cell;
}

- (CGFloat)getLabelHeightWithText:(NSString *)text width:(CGFloat)width font: (CGFloat)font
{
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil];
    
    return rect.size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 140 * KscreenHeight;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    AdetailViewController *adetailVC =  [[AdetailViewController alloc]init];
//
//    adetailVC.course_id = [_weikeArray[indexPath.row] valueForKey:@"id"];
//
//    [self.navigationController pushViewController:adetailVC animated:YES];
    
    [Helper keChengDetailFromVC:self course_id:[_weikeArray[indexPath.row] valueForKey:@"id"]];
    
    NSLog(@"%zd",indexPath.row);
    
}


-(void)weiKeAction{
    _page = 1;
    _isWeiKe = YES;
    _leftLineView.hidden = NO;
    _rightLineView.hidden = YES;
    
    _weikeArray = [NSMutableArray array];
    
    [self loadData];
    
    //回到tableview顶部
//    NSIndexPath* indexPat = [NSIndexPath indexPathForRow:0 inSection:0];
//    [self.tableView scrollToRowAtIndexPath:indexPat atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
}

-(void)zhiBoKeAction{
    _page = 1;
    _isWeiKe = NO;
    _leftLineView.hidden = YES;
    _rightLineView.hidden = NO;

    _weikeArray = [NSMutableArray array];
    
    [self loadData];
    
     //回到tableview顶部
//    NSIndexPath* indexPat = [NSIndexPath indexPathForRow:0 inSection:0];
//    [self.tableView scrollToRowAtIndexPath:indexPat atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
}

-(void)setUI{
    
    _weiKeBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _weiKeBtn.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth / 2, 50 * KscreenWidth);
    [_weiKeBtn setTitleColor:ZhuTiColor forState:0];
    [_weiKeBtn setTitle:@"微课" forState:0];
    [_weiKeBtn addTarget:self action:@selector(weiKeAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_weiKeBtn];
    
    _leftLineView = [[UIView alloc]initWithFrame:CGRectMake((ScreenWidth / 2 - 80 * KscreenWidth) / 2, NAVIGATION_BAR_HEIGHT + 47 * KscreenHeight, 80 * KscreenWidth, 3 * KscreenHeight)];
    _leftLineView.backgroundColor = ZhuTiColor;
    [self.view addSubview:_leftLineView];
    
    _zhiBoKeBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _zhiBoKeBtn.frame = CGRectMake(ScreenWidth / 2, NAVIGATION_BAR_HEIGHT, ScreenWidth / 2, 50 * KscreenWidth);
    [_zhiBoKeBtn setTitleColor:ZhuTiColor forState:0];
    [_zhiBoKeBtn setTitle:@"直播课" forState:0];
    [_zhiBoKeBtn addTarget:self action:@selector(zhiBoKeAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_zhiBoKeBtn];
    
    _rightLineView = [[UIView alloc]initWithFrame:CGRectMake((ScreenWidth / 2 - 80 * KscreenWidth) / 2 + ScreenWidth / 2, NAVIGATION_BAR_HEIGHT + 47 * KscreenHeight, 80 * KscreenWidth, 3 * KscreenHeight)];
    _rightLineView.hidden = YES;
    _rightLineView.backgroundColor = ZhuTiColor;
    
    [self.view addSubview:_rightLineView];
    
    UIView *zhongjianline = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth / 2, 10 * KscreenWidth + NAVIGATION_BAR_HEIGHT, 1 * KscreenWidth, 30 * KscreenHeight)];
    zhongjianline.backgroundColor = hui1Color;
    [self.view addSubview:zhongjianline];
    
    UIView *bottomline = [[UIView alloc]initWithFrame:CGRectMake(0, 50 * KscreenWidth  + NAVIGATION_BAR_HEIGHT, ScreenWidth, 1 * KscreenHeight)];
    bottomline.backgroundColor = hui1Color;
    [self.view addSubview:bottomline];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

